import { orderConfirm, orderCreate, postOrderComputed } from '../../api/store.js';
import { getAddressDefault, getAddressDetail, getUserAccount } from '../../api/user.js';


var app = getApp();
const util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    textareaStatus: true,
    parameter: {
      'navbar': '1',
      'return': '1',
      'title': '提交订单',
      'color': true,
      'class': '0'
    },
    //支付方式
    paywayArr: [
      { "name": "微信支付", "icon": "icon-weixin2", value: 'weixin', title: '微信快捷支付' }
    ],
    cartInfo: [],//购物车信息
    payType: 'weixin',//支付方式
    active: 0,//支付方式切换    
    address: { address: false },//地址组件
    addressInfo: {},//地址信息
    addressId: 0,//地址id
    cartId: '',//购物车id
    orderKey: "",//订单key
    mark: '',//备注信息
    useIntegral: false,//是否使用积分
    integral: 0,//用户积分
    integralPrice: 0,//积分抵扣金额
    useCash: false, //是否使用余额
    cash: 0, //余额
    cashPrice: 0, ////余额抵扣金额
    status: 0,
    isClose: false,
    toPay: false,//修复进入支付时页面隐藏从新刷新页面
    totalPostage: 0,//总邮费
    payPostage: 0, //需要支付的邮费
    totalPrice: 0, //商品总价
    totalPostage: 0, //总邮费,
    payPrice: 0, //合计，需要支付的价钱
  },
  /**
   * 授权回调事件
   * 
  */
  onLoadFun: function () {
    this.getaddressInfo();
    this.getConfirm();
    this.getUserAccount();
    //调用子页面方法授权后执行获取地址列表
    this.selectComponent('#address-window').getAddressList();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({ textareaStatus: true });
    if (app.globalData.isLog && this.data.isClose && this.data.toPay == false) {
      this.getaddressInfo();
      this.selectComponent('#address-window').getAddressList();
    }
  },
  computedPrice: function () {
    let shippingType = this.data.shippingType;
    postOrderComputed({
      unique: this.data.orderKey,
      useIntegral: this.data.useIntegral,
      useCash: this.data.useCash
    }).then(res => {
      this.setData({
        payPrice: res.data.payPrice,
        integralPrice: res.data.deductionIntegral,
        integral: res.data.integral,
        cashPrice: res.data.deductionCash,
        cash: res.data.cash,
        payPostage: res.data.payPostage
      });
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({ isClose: true });
  },
  changeTextareaStatus: function () {
    this.setData({ textareaStatus: true, status: 0 });
  },
  /**
   * 使用积分抵扣
  */
  ChangeIntegral: function () {
    this.setData({ useIntegral: !this.data.useIntegral });
    this.computedPrice();
  },
  /**
   * 使用余额抵扣
  */
  ChangeCash: function () {
    this.setData({ useCash: !this.data.useCash });
    this.computedPrice();
  },
  /**
   * 选择地址后改变事件
   * @param object e
  */
  OnChangeAddress: function (e) {
    this.setData({ textareaStatus: true, addressId: e.detail, 'address.address': false });
    this.getaddressInfo();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (!options.cartId) return app.Tips({ title: '请选择要购买的商品' }, { tab: 3, url: 1 });
    this.setData({
      cartId: options.cartId,
      addressId: options.addressId || 0,
    });
  },
  /**
   * 获取备注输入内容
   */
  bindHideKeyboard: function (e) {
    this.setData({ mark: e.detail.value });
  },
  /**
   * 获取当前订单详细信息
   * 
  */
  getConfirm: function () {
    var that = this;
    orderConfirm(this.data.cartId.split(",")).then(res => {
      that.setData({
        cartInfo: res.data.cartList,
        orderKey: res.data.orderKey,
        totalPostage: res.data.totalPostage,
        totalPrice: res.data.totalPrice,
        payPrice: res.data.totalPrice
      });
    }).catch(err => {
      return app.Tips({ title: err }, { tab: 3, url: 1 });
    });
  },
  /**
   * 获取用户账务信息
   * 
  */
  getUserAccount: function () {
    let that = this;
    getUserAccount().then(res => {
      that.setData({ cash: res.data.cash, integral: res.data.integral })
    })
  },
  /*
  * 获取默认收货地址或者获取某条地址信息
  */
  getaddressInfo: function () {
    var that = this;
    if (that.data.addressId) {
      getAddressDetail(that.data.addressId).then(res => {
        that.setData({ addressInfo: res.data || {}, addressId: res.data.id || 0, 'address.addressId': res.data.id || 0 });
      })
    } else {
      getAddressDefault().then(res => {
        that.setData({ addressInfo: res.data || {}, addressId: res.data.id || 0, 'address.addressId': res.data.id || 0 });
      })
    }
  },
  payItem: function (e) {
    var that = this;
    var active = e.currentTarget.dataset.index;
    that.setData({
      active: active,
      animated: true,
      payType: that.data.paywayArr[active].value,
    })
    setTimeout(function () {
      that.car();
    }, 500);
  },
  car: function () {
    var that = this;
    that.setData({
      animated: false
    });
  },
  onAddress: function () {
    this.setData({
      textareaStatus: false,
      'address.address': true,
      pagesUrl: '/packageB/user_address_list/index?cartId=' + this.data.cartId
    });
  },
  SubOrder: function (e) {
    var that = this, data = {};
    if (!this.data.payType) return app.Tips({ title: '请选择支付方式' });
    if (!this.data.addressId) return app.Tips({ title: '请选择收货地址' });
    data = {
      addressId: that.data.addressId,
      agentId: that.data.addressId,
      agentable: false,
      payType: that.data.payType,
      useIntegral: that.data.useIntegral,
      useCash: that.data.useCash,
      mark: that.data.mark,
      orderKey: this.data.orderKey,
      cartList: this.data.cartId.split(",")
    };
    wx.showLoading({ title: '订单支付中' });
    orderCreate(data).then(res => {
      var orderId = res.data.orderId, jsConfig = res.data.jsConfig,
        goPages = '/packageB/order_pay_status/index?order_id=' + orderId + '&msg=' + res.retMsg;
      switch (that.data.payType) {
        case 'weixin':
          if (jsConfig) {
            that.setData({ toPay: true });
            wx.requestPayment({
              timeStamp: jsConfig.timestamp,
              nonceStr: jsConfig.nonceStr,
              package: jsConfig.prepayId,
              signType: jsConfig.signType,
              paySign: jsConfig.paySign,
              success: function (res) {
                wx.hideLoading();
                if (that.data.BargainId || that.data.combinationId || that.data.pinkId || that.data.seckillId) return app.Tips({ title: '支付成功', icon: 'success' }, { tab: 4, url: goPages });
                return app.Tips({ title: '支付成功', icon: 'success' }, { tab: 5, url: goPages });
              },
              fail: function (e) {
                console.log(e);
                wx.hideLoading();
                return app.Tips({ title: '取消支付' }, { tab: 5, url: goPages + '&status=2' });
              },
              complete: function (e) {
                wx.hideLoading();
                //关闭当前页面跳转至订单状态
                if (res.errMsg == 'requestPayment:cancel') return app.Tips({ title: '取消支付' }, { tab: 5, url: goPages + '&status=2' });
              },
            })
          } else {
            wx.hideLoading();
            return app.Tips({ title: res.msg, icon: 'success' }, { tab: 5, url: goPages });
          }
          break;
        default:
          wx.hideLoading();
          return app.Tips({ title: res.msg, icon: 'success' }, { tab: 5, url: goPages });
          break;
      }
    }).catch(err => {
      console.log(err);
      wx.hideLoading();
      return app.Tips({ title: err });
    });
  }
})